package com.qf.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    //获得sqlSession工厂
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> t1 = new ThreadLocal<SqlSession>();

    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static SqlSession getSqlSession() {
        SqlSession session = t1.get();
        if (session == null) {
            session = factory.openSession();
            t1.set(session);
        }
        return session;
    }

    private static void closeSession() {
        SqlSession session = t1.get();
        session.close();
        t1.remove();
    }

    public static void commit() {
        SqlSession session = t1.get();
        session.commit();
        closeSession();
    }

    public static void rollback() {
        SqlSession session = t1.get();
        session.rollback();
        closeSession();
    }

    public static <T extends Object> T getMapper(Class<T> clazz){
        SqlSession session=getSqlSession();
        return session.getMapper(clazz);
    }



}
